package com.example.concurrency.exercise;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author: dangwen
 * @createDate: 2021/2/5
 */
public class ReentrantReadWriteLockDemo {
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    Lock writeLock = readWriteLock.writeLock();
    Lock readLock = readWriteLock.readLock();

    public void read() {
        readLock.lock();
        try {
            System.out.println("线程 " + Thread.currentThread().getName() + " 准备!!");
            Thread.sleep(5000);
            System.err.println("线程 " + Thread.currentThread().getName() + " 读1执行完毕。。。");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
    }
    public void read2() {
        readLock.lock();
        try {
            System.out.println("线程 " + Thread.currentThread().getName() + " 准备!!");
            Thread.sleep(2000);
            System.err.println("线程 " + Thread.currentThread().getName() + " 读2执行完毕。。。");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
    }

    public void write() {
        writeLock.lock();
        try {
            System.out.println("线程 " + Thread.currentThread().getName() + " 准备!!");
            Thread.sleep(1000);
            System.err.println("线程 " + Thread.currentThread().getName() + " 写执行完毕。。。");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantReadWriteLockDemo urwLock = new ReentrantReadWriteLockDemo();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                urwLock.read();
            }
        }, "t1");

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                urwLock.read2();
            }
        }, "t2");

        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                urwLock.write();
            }
        }, "t3");

        t3.start();
        t1.start();
        t2.start();
    }


}
